import React, {ReactNode, useRef} from "react";

interface CacheProps {
  activeKey: string;
  children: ReactNode[];
}

const Cache: React.FC<CacheProps> = ({activeKey, children}) => {
  // 用 ref 缓存所有渲染过的 child
  const cacheRef = useRef<{[key: string]: ReactNode}>({});

  // 遍历 children，缓存每个 child
  React.Children.forEach(children, (child: any) => {
    if (child && child.key != null) {
      cacheRef.current[child.key as string] = child;
    }
  });

  return (
    <>
      {Object.entries(cacheRef.current).map(([key, child]) => (
        <div key={key} style={{display: key === activeKey ? "block" : "none", width: "100%", height: "100%"}}>
          {child}
        </div>
      ))}
    </>
  );
};

export default Cache;
